import UIKit
import SnapKit

class Module2ViewController: BaseViewController {
    
    private let tableView = UITableView()
    private var sections: [SectionData] = []
    private var expandedSection: Int? = nil
    private var cellHeights: [IndexPath: CGFloat] = [:]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        title = "模块2"
        setupData()
        setupTableView()
    }
    
    private func setupData() {
        // 创建5个section，每个section有随机的cell数量
        sections = [
            SectionData(title: "Section 1", cells: Array(1...Int.random(in: 3...6)).map { "Cell \($0)" }),
            SectionData(title: "Section 2", cells: Array(1...Int.random(in: 3...6)).map { "Cell \($0)" }),
            SectionData(title: "Section 3", cells: Array(1...Int.random(in: 3...6)).map { "Cell \($0)" }),
            SectionData(title: "Section 4", cells: Array(1...Int.random(in: 3...6)).map { "Cell \($0)" }),
            SectionData(title: "Section 5", cells: Array(1...Int.random(in: 3...6)).map { "Cell \($0)" })
        ]
    }
    
    private func setupTableView() {
        view.addSubview(tableView)
        tableView.backgroundColor = .clear
        tableView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.left.right.bottom.equalToSuperview()
        }
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(ExpandableCell.self, forCellReuseIdentifier: "ExpandableCell")
        tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "Header")
    }
}

// MARK: - UITableViewDataSource
extension Module2ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].cells.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ExpandableCell", for: indexPath) as! ExpandableCell
        cell.configure(with: sections[indexPath.section].cells[indexPath.row])
        
        // 设置cell的展开状态
        let isExpanded = expandedSection == indexPath.section
        cell.setExpanded(isExpanded, animated: false)
        
        return cell
    }
}

// MARK: - UITableViewDelegate
extension Module2ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Header")
        headerView?.textLabel?.text = sections[section].title
        headerView?.textLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        headerView?.backgroundColor = .gray
        headerView?.textLabel?.textColor = .black
        
        // 添加点击手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(headerTapped(_:)))
        headerView?.addGestureRecognizer(tapGesture)
        headerView?.tag = section
        
        return headerView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let isExpanded = expandedSection == indexPath.section
        return isExpanded ? 60 : 0 // 展开时60高度，收起时0高度
    }
    
    @objc private func headerTapped(_ gesture: UITapGestureRecognizer) {
        guard let headerView = gesture.view,
              let section = headerView.tag as Int? else { return }
        
        let wasExpanded = expandedSection == section
        let newExpandedSection = wasExpanded ? nil : section
        
        // 使用 performBatchUpdates 实现平滑动画
        tableView.performBatchUpdates({
            // 收起之前展开的section
            if let previousExpanded = expandedSection, previousExpanded != section {
                let previousIndexPaths = sections[previousExpanded].cells.enumerated().map { 
                    IndexPath(row: $0.offset, section: previousExpanded) 
                }
                // 将之前展开的cells高度设为0
                for indexPath in previousIndexPaths {
                    if let cell = tableView.cellForRow(at: indexPath) as? ExpandableCell {
                        cell.setExpanded(false, animated: true)
                    }
                }
            }
            
            // 设置新的展开状态
            expandedSection = newExpandedSection
            
            // 展开新点击的section
            if !wasExpanded {
                let newIndexPaths = sections[section].cells.enumerated().map { 
                    IndexPath(row: $0.offset, section: section) 
                }
                // 将新展开的cells高度设为60
                for indexPath in newIndexPaths {
                    if let cell = tableView.cellForRow(at: indexPath) as? ExpandableCell {
                        cell.setExpanded(true, animated: true)
                    }
                }
            }
        }, completion: nil)
    }
}

// MARK: - ExpandableCell
class ExpandableCell: UITableViewCell {
    private let titleLabel = UILabel()
    private let detailView = UIView()
    private var heightConstraint: NSLayoutConstraint?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = .systemGray6
        
        // 添加标题标签
        contentView.addSubview(titleLabel)
        titleLabel.font = UIFont.systemFont(ofSize: 16)
        titleLabel.textColor = .black
        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
        }
        
        // 添加详情视图
        contentView.addSubview(detailView)
        detailView.backgroundColor = .systemBlue.withAlphaComponent(0.1)
        detailView.layer.cornerRadius = 8
        detailView.snp.makeConstraints { make in
            make.left.equalTo(titleLabel.snp.right).offset(16)
            make.right.equalToSuperview().offset(-16)
            make.centerY.equalToSuperview()
            make.height.equalTo(40)
        }
        
        // 初始状态：详情视图高度为0
        detailView.snp.updateConstraints { make in
            make.height.equalTo(0)
        }
    }
    
    func configure(with title: String) {
        titleLabel.text = title
    }
    
    func setExpanded(_ expanded: Bool, animated: Bool) {
        let duration: TimeInterval = animated ? 0.3 : 0
        
        UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: {
            self.detailView.snp.updateConstraints { make in
                make.height.equalTo(expanded ? 40 : 0)
            }
            self.contentView.layoutIfNeeded()
        }, completion: nil)
    }
}

// MARK: - Section Data Model
struct SectionData {
    let title: String
    let cells: [String]
} 
